﻿using CardPlay.Model.ActionModel;
using CardPlay.Model.CardModel;
using CardPlay.Model.GameModel;
using CardPlay.Model.GameModel.Presentation;
using CardPlay.Model.Layout;
using CardPlay.Model.Primitives;

namespace CardPlay.DemoPack.Games.PairingVariants
{
    [Game("C4D5FA05-39E2-4B4E-B2D4-E9E06730CFAC", LevelOfDifficulty.Easy, LevelOfSkill.ChanceOnly, DurationOfPlay.LessThan5Minutes, Family = FamilyName)]
    public class Pairs : PairingStyleGame
    {
        public Pairs()
        {
            NamesOfAdditionalPiles.AddRange(new[] {Stock, Waste});
            TotalTableaus = 9;
        }

        protected override bool IsOver
        {
            get { return !this[Waste].IsEmpty && !SetHasPair(this.NonEmptyPilesNamed(AnyTableau + "|" + Waste)); }
        }

        public override ILayoutSite CreatePresentation(IPresentationContext presentation)
        {
            var root = presentation.CreateRowLayout();

            var stockWaste = presentation.CreateStockWasteLayout(this);
            root.Add(stockWaste);

            stockWaste.Direction = SpreadDirection.Vertical;

            var style = new VisualTraits
                        {
                            HorizontalAlignment = HorizontalAlignment.Center,
                            VerticalAlignment = VerticalAlignment.Center,
                            Arrangement = CardArrangement.StackSquare,
                            MinimumSize = presentation.Metrics.CardSize + new Size(presentation.Metrics.MinSpacingAcross, presentation.Metrics.MinSpacingDown)
                        };

            var tableau = new UniformGridLayout { Columns = 3, Rows = 3 };
            root.Add(tableau);

            presentation.AddPiles(tableau, NamesOfTableaus, style);

            return root;
        }

        protected override void PrepareDealScript(DealScript script)
        {
            script.DealToEach(NamesOfTableaus, "up");
            script.DealRemainingFaceDownTo(Stock);
        }

        protected override IAction QueryActionAt(PartLocation location)
        {
            return location.Matches(Stock) && SetHasPair(this.NonEmptyPilesNamed(AnyTableau))
                ? null
                : base.QueryActionAt(location);
        }

        protected override void OnTransactionEnding()
        {
            this.FillEmptyPilesMatching(AnyTableau, this[Stock]);
        }
    }
}